import { action, configure, observable, reaction, runInAction } from "mobx";
import { navigator } from "../utils";
import { setUploadLocationTimer } from "../utils/util";
import ToastUtils from "../utils/ToastUtils";
import { routes } from '../net/common'
import { startSeekOrderNotification, getSeekOrderCount } from "../plugins/SeekOrderNotification";
import { logger } from "../utils/util";
import backgroundTimePlugin from "../plugins/backgroundTimer";
import { hasPermissionCode } from "../utils/permission";

configure({
  // enforceActions: 'always'
});

class Store {

  @observable userInfo = {};
  @observable errorLog = [];//异常日志
  @observable location = {};
  @observable session = "";
  @observable areas = [];
  @observable uploadFailList = [];//上传失败列表
  @observable selectCity = {};
  @observable topList = [];
  @observable recordingNo = '';
  @observable playingNo = '';
  @observable showRecorder = false; //是否显示录音界面
  @observable showPlayer = ''; //是否显示播放器(不为空显示）
  @observable showPage = ''; //是显示在首页或者订单详情页
  @observable timeOrderCount = 0;
  @observable complaintOrderCount = 0;
  @observable seekOrderCount = 0; // 咨询工单记录
  @observable permissionList = []; // 权限列表
  @observable isSeekOrderTip = false; // 咨询工单处理弹窗

  @action.bound
  setValue(keys, data) {
    this[keys] = data;
  }

  @action.bound
  getUserInfo() {
    axios.post(api.userInfo)
      .then(result => {
        runInAction(() => {
          logger("用户信息", result);
          if (result.body) {
            this.userInfo = result.body;
          } else {
            this.userInfo = {};
          }
        });
      }).catch(logger);
  }

  @action.bound
  getTreeList() {
    axios.post(api.treeList, { body: {} })
      .then(result => {
        runInAction(() => {
          if (result.body) {
            this.areas = result.body;
          } else {
            this.areas = [];
          }
        });
      }).catch(logger);
  }

  @action.bound
  getAgencyInfo(id) {
    axios.post(api.agencyDetail, { body: { id }, showLoading: true })
      .then(result => {
        runInAction(() => {
          logger("机构信息", result);
          if (result.body) {
            this.agencyInfo = result.body;
            navigator.navigate("AgencyMgr");
          } else {
            this.agencyInfo = {};
          }
        });
      }).catch(e => e.msg && ToastUtils.showFailInfo(e.msg));
  }



  @action.bound
  clearInfoAndJumpToLogin() {
    this.session = "";
    this.userInfo = {};
    this.recordingNo = '';
    this.playingNo = '';
    this.permissionList = [];
    token = null;
    navigator.resetToLoginPage();
    backgroundTimePlugin.clear();
    backgroundTimePlugin.reset();
  }

  @action.bound
  async logout() {
    // await axios.post(api.sign_out).catch(logger);
    // runInAction(() => {
    this.clearInfoAndJumpToLogin();
    // });
  }
}

const userStore = new Store();
reaction(() => userStore.session, (data) => {
  logger("登录信息", data);
  //设置全局并存储到本地
  token = !IsNullOrEmpty(data) ? data.token : "";
  if (data) {
    storage.save({
      key: "session",
      data: data,
    }).catch(logger);
    userStore.setValue('userInfo',data.customer)
  }

  // if (!IsNullOrEmpty(data)) {
  //     setTimeout(() => userStore.getUserInfo(), 1000)
  // }
});

reaction(() => userStore.userInfo, (data) => {
  if (data && data.distributorId) {
    // 上传定位
    setUploadLocationTimer(true, 50 * 1000);
    // 获取路由
    routes().then(res => {
      const menus = res.result || []
      const hasSeekOrderPermission = hasPermissionCode(menus, 'delivery_seek_order_tip');
      if (hasSeekOrderPermission) {
        getSeekOrderCount();
        startSeekOrderNotification();
        const perList = userStore.permissionList.includes('seekOrder') ? userStore.permissionList : userStore.permissionList.concat('seekOrder')
        userStore.setValue('permissionList', perList)
      } else {
        userStore.setValue('permissionList', userStore.permissionList.filter(item => item != 'seekOrder'))
      }
    })
  }
});

reaction(() => userStore.topList, (data) => {
    storage.save({
      key: "topList",
      data: data||[],
    }).catch(logger);
});
reaction(() => userStore.recordingNo, (data) => {
    storage.save({
      key: "recordingNo",
      data: data||'',
    }).catch(logger);
});

reaction(() => userStore.uploadFailList, (data) => {
    storage.save({
      key: "uploadFailList",
      data: data||[],
    }).catch(logger);
});
reaction(() => userStore.errorLog, (data) => {
  logger('存储日志',JSON.stringify(data))
    storage.save({
      key: "errorLog",
      data: data||[],
    }).catch(logger);
});

export default userStore;
